package com.pt25.base.dep.swagger;

import com.pt25.base.constants.BaseConstants;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;


/**
 * spring doc 公共配置类
 */
@Configuration
@ConditionalOnProperty(name = "springdoc.api-docs.enabled", havingValue = "true")
public class SpringDocConfig {

    @Value("${server.port}")
    private String port;

    @Value("${spring.application.name}")
    private String appName;

    @Value("${springdoc.gateway-url}")
    private String gatewayUrl;

    @Bean
    @ConfigurationProperties(prefix = "springdoc.api-docs.info")
    public Info springDocInfo() {
        return new Info();
    }

    /**
     * 微服务地址：是单个微服务swagger访问地址，主要用来本地测试
     * 网关服务地址: 是网关聚合swagger api时的地址，主要用来提供统一对外的swagger api,其中9911是网关的地址
     * localhost 要改成微服务或网关的地址
     */
    @Bean
    public OpenAPI openAPI(Info infoConfig) {
        // 动态获取服务器信息
        OpenAPI openAPI = new OpenAPI().info(infoConfig);
        // header头中添加Authorization字段用来传token
        openAPI.components(new Components().addSecuritySchemes(BaseConstants.AUTHORIZATION, new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT")));
        openAPI.addSecurityItem(new SecurityRequirement().addList(BaseConstants.AUTHORIZATION));
        openAPI.servers(List.of(
//                new Server()
//                        .url("http://" + IpUtil.getAllLocalIps().get(0) + ":" + port)
//                        .description("微服务地址"),
                new Server()
                        .url("http://localhost:" + port)
                        .description("微服务地址"),
                new Server()
                        .url("http://" + gatewayUrl + "/" + appName)
                        .description("网关服务地址")
        ));
        return openAPI;
    }

}
